﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPPEI.Coolzon.Core;
using CPPEI.Coolzon.Core.Repositories;

namespace CPPEI.Coolzon.ManagementCenter
{
    public partial class PrivilegeList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            using (DbContext context = new DbContext())
            {
                IPrivilegeRepository privilegeRepository = RepositoryFactory.Create<IPrivilegeRepository>();

                PagedList<CPPEI.Coolzon.Core.Data.Privilege> privilegeList = privilegeRepository.GetPrivilegeList(context, 0, int.MaxValue);
                gvUserList.DataSource = privilegeList.DataList;
                gvUserList.DataBind();
            }
        }

        protected void gvPrivilegeList_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string Id = ((Label)gvUserList.Rows[e.NewEditIndex].FindControl("lblId")).Text.Trim();
            Response.Redirect("EditPrivilege.aspx?Id=" + Id, false);
        }

        protected void gvPrivilegeList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            using (DbContext context = new DbContext())
            {
                IPrivilegeRepository privilegeRepository = RepositoryFactory.Create<IPrivilegeRepository>();
                IAssignedPrivilegeRepository iAssignedPrivilegeRepository = RepositoryFactory.Create<IAssignedPrivilegeRepository>();
                string Id = ((Label)gvUserList.Rows[e.RowIndex].FindControl("lblId")).Text.Trim();
                CPPEI.Coolzon.Core.Data.Privilege privilege = new CPPEI.Coolzon.Core.Data.Privilege();
                privilege.Id = new Guid(Id);
                CPPEI.Coolzon.Core.Data.AssignedPrivilege assignedPrivilege = new Core.Data.AssignedPrivilege();
                assignedPrivilege.Id = new Guid(Id);
                if (privilegeRepository.RemovePrivilege(context, privilege) && iAssignedPrivilegeRepository.RemoveAssignedPrivilege(context, assignedPrivilege))
                {
                    LoadData();
                }
            }
        }

        protected void Add_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddPrivilege.aspx", false);
        }
    }
}